import { useMemo, useState } from "react";
import { Button } from 'react-vant';
const UseMemoDemo = () => {
    const [count, setCount] = useState(0)
    const [dep, setDep] = useState(0)
    const ChangeCount = () => {
        setCount(count + 1)
    }
    const ChangeDep = () => {
        setDep(dep + 1)
    }
    const total = () => {
        console.log('没有缓存的变量方法');
        return 2 * count
    }
    const memoTotal = useMemo(() => {
        console.log('被缓存的变量方法');
        return 2 * count
    }, [count])

    //如果返回的是一个函数可以使用useCallback
    // const memoTotal = useMemo(() => {
    //     return () => {
    //         console.log('被缓存的变量方法');
    //         return 2 * count
    //     }
    // }, [count])

    // const memoTotal = useCallback(() => {
    //     console.log('被缓存的变量方法');
    //     return 2 * count
    // })

    return (
        <>
            <h1>当count改变的时候会全部重新渲染</h1>
            <h1>当dep改变的时候只会部分渲染，count没有改变不会重复渲染</h1>
            <Button onClick={ChangeCount} type="info">
                count变量改变 | {count}
            </Button>
            <Button onClick={ChangeDep} type="danger">
                dep变量改变 | {dep}
            </Button>

            <h3>total: {total()}</h3>
            <h3>memo total: {memoTotal}</h3>
        </>
    )
}

export default UseMemoDemo